import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import qs from 'qs'
import { add2Cache,getFromCache, removeFromCache} from '@/utils/cache'
const baseUrl = window.configs.api.baseUrl
// axios.defaults.timeout = 5000;
axios.defaults.baseURL = baseUrl;
axios.defaults.responseType ="json";
axios.defaults.headers["Content-Type"]="application/x-www-form-urlencoded;charset=UTF-8";
//http request 拦截器
axios.interceptors.request.use(
  config => {
		console.log(config)
    // const token = getCookie('名称');注意使用的时候需要引入cookie方法，推荐js-cookie
	  if(config.headers["Content-Type"]=="multipart/form-data;charset=utf-8"){
			console.log(config)
			 config.data = config.data
			 return config
		 }else{
			console.log(config)
			config.data = qs.stringify(config.data)
			 return config
		 }
    return config;
  },
  error => {
    return Promise.reject(err);
  }
);


//http response 拦截器
axios.interceptors.response.use(
  response => {
    // if(response.data.errCode ==2){
    //   router.push({
    //     path:"/login",
    //     querry:{redirect:router.currentRoute.fullPath}//从哪个页面跳转
    //   })
    // }
		console.log(response)
    return response;
  },
  error => {
		 Message({
		  message: '登录连接超时（后台不能连接，请联系系统管理员）',
		  type: 'error',
		  duration: 5 * 1000
		})
    return Promise.reject(error)
  }
)


/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export async function fetch(url,params={}){
  return await new Promise((resolve,reject) => {
    axios.get(url,{
      params:params
    })
    .then(response => {
      resolve(response.data);
    })
    .catch(err => {
      reject(err)
    })
  })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

 export async function  post(url,data = {}){
   return await new Promise((resolve,reject) => {
     axios.post(url,data)
          .then(response => {
						console.log(response)
            resolve(response.data);
          },err => {
            reject(err)
          })
   })
 }

 /**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export async function patch(url,data = {}){
  return await new Promise((resolve,reject) => {
    axios.patch(url,data)
         .then(response => {
           resolve(response.data);
         },err => {
           reject(err)
         })
  })
}

 /**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export async function put(url,data = {}){
  return await new Promise((resolve,reject) => {
    axios.put(url,data)
         .then(response => {
           resolve(response.data);
         },err => {
           reject(err)
         })
  })
}

/* 用法 */
 // this.$fetch('/api/v2/movie/top250')
 //      .then((response) => {
 //        console.log(response)
 //      })
